<template>
  <div class="app-container">
    <el-form size="small" inline>
      <el-form-item label="姓名">
        <el-input v-model="query.name" placeholder="请输入姓名" clearable />
      </el-form-item>
      <el-form-item label="身份证号">
        <el-input v-model="query.idcardNumber" placeholder="请输入身份证号" clearable />
      </el-form-item>
      <el-form-item label="所属地区">
        <agriculture-region :value.sync="query.region" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" @click="getList">查询</el-button>
        <el-button plain icon="el-icon-refresh" @click="handleReset"> 重置</el-button>
        <el-button plain icon="el-icon-plus" type="success" @click="dialogVisible = true">新增</el-button>
        <help></help>
      </el-form-item>
    </el-form>
    <el-table border v-loading="loading" :data="list">
      <el-table-column align="center" label="姓名" prop="name" min-width="80" />
      <el-table-column align="center" label="所属地区" prop="deptId" min-width="110" show-overflow-tooltip>
        <template slot-scope="scope">
          <agriculture-region :value.sync="scope.row.deptId" type="text" />
        </template>
      </el-table-column>
      <el-table-column align="center" label="联系方式" prop="phone" min-width="110" />
      <el-table-column align="center" label="身份证号" prop="idcardNumber" min-width="120" />
      <el-table-column align="center" label="地址" prop="address" min-width="130" show-overflow-tooltip />
      <el-table-column align="center" label="经营田地（亩）" min-width="100" />
      <el-table-column align="center" label="操作" min-width="110">
        <template slot-scope="scope">
          <el-button
            type="text"
            size="small"
            icon="el-icon-document"
            @click="detailPersonManage(scope.row.manageId, true)"
            >详情
          </el-button>
          <el-button type="text" size="small" icon="el-icon-edit" @click="detailPersonManage(scope.row.manageId, false)"
            >编辑
          </el-button>
          <el-button type="text" size="small" icon="el-icon-delete" @click="deletePersonManage(scope.row.manageId)"
            >删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="query.pageNum"
      :limit.sync="query.pageSize"
      @pagination="getList"
    />

    <help-dialog :title="title" :visible.sync="dialogVisible" @close="closeDialog">
      <el-form size="small" label-width="130px" ref="form" :model="queryParam" :rules="rules">
        <div class="label">经营户信息</div>
        <el-row>
          <el-col :span="12">
            <el-form-item label="姓名" prop="name">
              <el-input v-model="queryParam.name" placeholder="请输入姓名" clearable :disabled="disabled" />
            </el-form-item>
            <el-form-item label="联系方式" prop="phone">
              <el-input
                v-model="queryParam.phone"
                maxlength="11"
                placeholder="请输入联系方式"
                clearable
                :disabled="disabled"
              />
            </el-form-item>
            <el-form-item label="身份证正面" prop="file1">
              <y-show-all-file v-if="disabled" :path="queryParam.file1"></y-show-all-file>
              <y-upload
                v-else
                accept=".jpeg,.jpg,.png"
                limit="1"
                :path="[queryParam.file1]"
                ref="file1"
                @onSuccess="successCardFile($event, 'file1')"
              ></y-upload>
            </el-form-item>
            <el-form-item label="详细地址" prop="address">
              <el-input v-model="queryParam.address" placeholder="请输入详细地址" clearable :disabled="disabled" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="所属地区" prop="deptId">
              <agriculture-region :value.sync="queryParam.deptId" :disabled="disabled" />
            </el-form-item>
            <el-form-item label="身份证号" prop="idcardNumber">
              <el-input
                v-model="queryParam.idcardNumber"
                placeholder="请输入身份证号"
                maxlength="18"
                clearable
                :disabled="disabled"
              />
            </el-form-item>
            <el-form-item label="身份证反面" prop="file2">
              <y-show-all-file v-if="disabled" :path="queryParam.file2"></y-show-all-file>
              <y-upload
                v-else
                accept=".jpeg,.jpg,.png"
                limit="1"
                :path="[queryParam.file2]"
                ref="file2"
                @onSuccess="successCardFile($event, 'file2')"
              ></y-upload>
            </el-form-item>
          </el-col>
        </el-row>
        <!-- <div class="label">土地信息</div>
        <el-row>
          <el-col :span="12">
            <el-form-item label="土地编码/地宗号" prop="landCode">
              <el-input
                v-model="queryParam.landCode"
                placeholder="请输入土地编码/地宗号"
                @input="changeLandCode"
                clearable
                :disabled="disabled"
              />
            </el-form-item>
            <el-form-item label="面积（亩）" prop="area">
              <el-input v-model="queryParam.area" :disabled="read" placeholder="请输入面积（亩）" clearable />
            </el-form-item>
            <el-form-item label="坐标（东至）" prop="east">
              <el-input v-model="queryParam.east" :disabled="read" placeholder="请输入坐标（东至）" />
            </el-form-item>
            <el-form-item label="坐标（南至）" prop="south">
              <el-input v-model="queryParam.south" :disabled="read" placeholder="请输入坐标（南至）" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="所属地区" prop="areaCode">
              <agriculture-region :value.sync="queryParam.areaCode" :disabled="read" />
            </el-form-item>
            <el-form-item label="是否农田" prop="basicLand">
              <el-select
                v-model="queryParam.basicLand"
                :disabled="read"
                placeholder="请选择是否基本农田"
                clearable
                style="width: 100%"
              >
                <el-option
                  v-for="item in dict.type.agriculture_basic_land"
                  :key="item.value"
                  :value="item.value"
                  :label="item.label"
                ></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="坐标（西至）" prop="west">
              <el-input v-model="queryParam.west" :disabled="read" placeholder="请输入坐标（西至）" />
            </el-form-item>
            <el-form-item label="坐标（北至）" prop="north">
              <el-input v-model="queryParam.north" :disabled="read" placeholder="请输入坐标（北至）" />
            </el-form-item>
          </el-col>
        </el-row>
        <div class="label">转让信息</div>
        <el-row>
          <el-col :span="12">
            <el-form-item label="转出方" prop="transferor">
              <el-input v-model="queryParam.transferor" placeholder="请输入转出方" clearable :disabled="disabled" />
            </el-form-item>
            <el-form-item label="流转方式" prop="circulationType">
              <el-select
                v-model="queryParam.circulationType"
                placeholder="请选择流转方式"
                clearable
                :disabled="disabled"
                style="width: 100%"
              >
                <el-option
                  v-for="item in dict.type.circulation_type"
                  :key="item.value"
                  :value="item.value"
                  :label="item.label"
                ></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="流转费（亩）" prop="circulationFee">
              <el-input
                v-model="queryParam.circulationFee"
                placeholder="请输入流转费（亩）"
                clearable
                :disabled="disabled"
              />
            </el-form-item>
            <el-form-item label="合同附件" prop="contractFile">
              <y-show-all-file v-if="disabled" :path="queryParam.contractFile"></y-show-all-file>
              <y-upload
                v-else
                accept=".jpeg,.jpg,.png,.pdf,.doc,.docx"
                limit="1"
                ref="contractFile"
                :path="[queryParam.contractFile]"
                @onSuccess="successCardFile($event, 'contractFile')"
              ></y-upload>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="所属地区" prop="transferorArea">
              <agriculture-region :value.sync="queryParam.transferorArea" :disabled="disabled" />
            </el-form-item>
            <el-form-item label="经营期限" prop="manageTime">
              <el-input v-model="queryParam.manageTime" placeholder="请输入经营期限" clearable :disabled="disabled" />
            </el-form-item>
            <el-form-item label="总计（元）" prop="total">
              <el-input v-model="queryParam.total" placeholder="请输入" clearable :disabled="disabled" />
            </el-form-item>
          </el-col>
        </el-row> -->
      </el-form>
      <span slot="footer" class="dialog-footer" v-show="!disabled">
        <el-button @click="closeDialog">取 消</el-button>
        <el-button v-if="queryParam.manageId" type="primary" @click="updatePersonManage">更 新</el-button>
        <el-button v-else type="primary" @click="addPersonManage">确 定</el-button>
      </span>
    </help-dialog>
  </div>
</template>

<script>
import personApi from '@/api/manage/person'
import landApi from '@/api/land/land'
import { debounce } from '@/utils/common'
import AgricultureRegion from '@/components/AgricultureRegion/AgricultureRegion'

export default {
  dicts: ['agriculture_basic_land', 'circulation_type'],
  components: { AgricultureRegion },
  data() {
    return {
      loading: false,
      list: [],
      title: '个人经营添加',
      disabled: false,
      dialogVisible: false,
      query: {
        name: '',
        region: '',
        idcardNumber: '',
        pageNum: 1,
        pageSize: 10
      },
      total: 0,
      queryParam: {
        name: '',
        phone: '',
        address: '',
        idcardNumber: '',
        cardFile: '',
        landCode: '',
        west: '',
        east: '',
        south: '',
        north: '',
        basicLand: '',
        deptId: '',
        manageTime: '',
        total: '',
        areaCode: '',
        contractFile: '',
        transferorArea: '',
        circulationFee: '',
        circulationType: '',
        transferor: '',
        file1: undefined,
        file2: undefined
      },
      read: false,
      rules: {
        name: [{ required: true, message: '请输入姓名', trigger: 'blur' }],
        phone: [{ required: true, message: '请输入联系方式', trigger: 'blur' }],
        area: [{ required: true, message: '请输入面积（亩）', trigger: 'blur' }],
        idcardNumber: [
          { required: true, message: '请输入身份证号', trigger: 'blur' },
          { min: 18, max: 18, message: '请输入正确的身份证' }
        ],
        file1: [{ required: true, message: '请上传身份证正面', trigger: 'blur' }],
        file2: [{ required: true, message: '请上传身份证反面', trigger: 'blur' }],
        landCode: [{ required: true, message: '请输入土地编码/地宗号', trigger: 'blur' }],
        deptId: [{ required: true, message: '请输入所属地区', trigger: 'blur' }],
        transferor: [{ required: true, message: '请输入转出方', trigger: 'blur' }],
        circulationType: [{ required: true, message: '请选择流转方式', trigger: 'blur' }],
        areaCode: [{ required: true, message: '请输入所属地区', trigger: 'blur' }],
        transferorArea: [{ required: true, message: '请输入所属地区', trigger: 'blur' }]
      }
    }
  },
  created() {
    this.getList()
  },
  methods: {
    getList() {
      this.loading = true
      personApi.personManageList(this.query).then((res) => {
        this.list = res.rows
        this.total = res.total
        this.loading = false
      })
    },
    handleReset() {
      this.query = {
        name: '',
        area: '',
        idcardNumber: '',
        pageNum: 1,
        pageSize: 10
      }
      this.getList()
    },
    closeDialog() {
      if (!this.disabled) {
        this.$refs.file1.clearFiles()
        this.$refs.file2.clearFiles()
        // this.$refs.contractFile.clearFiles()
      }
      this.$refs.form.clearValidate()

      this.dialogVisible = false
      this.disabled = false
      this.read = false
      this.queryParam = {
        name: '',
        phone: '',
        address: '',
        idcardNumber: '',
        cardFile: '',
        landCode: '',
        west: '',
        east: '',
        south: '',
        north: '',
        basicLand: '',
        deptId: '',
        manageTime: '',
        total: '',
        areaCode: '',
        contractFile: '',
        transferorArea: '',
        circulationFee: '',
        circulationType: '',
        transferor: '',
        file1: undefined,
        file2: undefined
      }
    },
    successCardFile(file, val) {
      this.queryParam[val] = file.router
    },
    changeLandCode: debounce(function (val) {
      // 搜索土地编码/地宗号 数据回显
      landApi.landInfo({ landCode: val }).then((res) => {
        if (res.data) {
          this.read = true

          this.queryParam = {
            ...this.queryParam,
            areaCode: res.data.deptId,
            east: res.data.east,
            west: res.data.west,
            south: res.data.south,
            north: res.data.north,
            area: res.data.area,
            basicLand: res.data.basicLand
          }
        } else this.read = false
      })
    }, 1000),
    addPersonManage() {
      this.$refs.form.validate(async (valid) => {
        if (valid) {
          // 当前土地不存在，新增土地
          if (!this.read) {
            await landApi.addLandData({
              landCode: this.queryParam.landCode,
              areaCode: this.queryParam.areaCode,
              east: this.queryParam.east,
              west: this.queryParam.west,
              south: this.queryParam.south,
              north: this.queryParam.north,
              area: this.queryParam.area,
              basicLand: this.queryParam.basicLand
            })
          }
          this.queryParam.cardFile = this.queryParam.file1 + ',' + this.queryParam.file2
          const { code } = await personApi.addPersonManage(this.queryParam)
          if (code == 200) {
            this.$message.success('添加成功')
            this.closeDialog()
            this.getList()
          }
        } else {
          return false
        }
      })
    },
    deletePersonManage(manageId) {
      this.$confirm('确认删除?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          personApi.deletePersonManage({ manageId: manageId }).then((res) => {
            this.$message.success('删除成功')
            this.getList()
          })
        })
        .catch(() => {
          this.$message.info('已取消删除')
        })
    },
    detailPersonManage(manageId, value) {
      personApi.detailPersonManage({ manageId: manageId }).then((res) => {
        this.queryParam = res.data
        this.read = true
        this.title = '个人经营详情'
        this.disabled = value
        this.dialogVisible = true
        if (!this.disabled) {
          this.$nextTick(() => {
            this.$refs.file1.getFileShow()
            this.$refs.file2.getFileShow()
            // this.$refs.contractFile.getFileShow()
          })
        }
      })
    },
    updatePersonManage() {
      this.$refs.form.validate(async (valid) => {
        if (valid) {
          // 当前土地不存在，新增土地
          if (!this.read) {
            await landApi.addLandData({
              landCode: this.queryParam.landCode,
              areaCode: this.queryParam.areaCode,
              east: this.queryParam.east,
              west: this.queryParam.west,
              south: this.queryParam.east,
              north: this.queryParam.west,
              area: this.queryParam.area,
              basicLand: this.queryParam.basicLand
            })
          }
          this.queryParam.cardFile = this.queryParam.file1 + ',' + this.queryParam.file2
          const { code } = await personApi.updatePersonManage(this.queryParam)
          if (code == 200) {
            this.$message.success('修改成功')
            this.closeDialog()
            this.getList()
          }
        } else {
          return false
        }
      })
    }
  }
}
</script>

<style scoped>
.label {
  font-size: 16px;
  font-weight: 700;
  color: #409eff;
  margin: 20px 0;
  border-left: 3px solid;
  padding-left: 5px;
  line-height: 20px;
}
</style>